#include "VCharts.h"
#include "ui_VCharts.h"
#include "VDialogProtocal.h"

VCharts::VCharts(QWidget *parent) :
    QCustomPlot(parent),
    ui(new Ui::VCharts)
{
    ui->setupUi(this);
    init();
}

VCharts::~VCharts()
{
    delete ui;
}

void VCharts::init()
{
    //初始化线
    this->axisRect()->setBackground(QBrush(Qt::white));//背景色
    QColor colorLightBlue = QColor("#e1e1e1");

    //网格设置
    this->xAxis->grid()->setZeroLinePen(QPen(Qt::black)); // x0线颜色
    this->xAxis->grid()->setPen(QPen(colorLightBlue, 1, Qt::PenStyle::SolidLine));
    this->yAxis->grid()->setZeroLinePen(QPen(Qt::black)); // y0线颜色
    this->yAxis->grid()->setPen(QPen(colorLightBlue, 1, Qt::PenStyle::SolidLine));
    this->yAxis->grid()->setSubGridVisible(true);
    //x轴设置
    this->xAxis->setSubTicks(false);       //关闭子刻度线显示
    this->xAxis->setTickLength(0);         //主刻度线长度为0
    this->xAxis->setBasePen(QPen(colorLightBlue));//轴颜色
    this->xAxis2->setVisible(true);        //显示x2轴
    this->xAxis2->setTickLabels(false);    //x2轴刻度不显示文本
    this->xAxis2->setSubTicks(false);
    this->xAxis2->setTicks(false);
    this->xAxis2->setBasePen(QPen(colorLightBlue));

    //y轴设置
    this->yAxis->setSubTicks(true);       //关闭子刻度线显示
    this->yAxis->setTickLength(0);         //主刻度线长度为0
    this->yAxis->setBasePen(QPen(colorLightBlue));//轴颜色
    this->yAxis2->setVisible(true);        //显示x2轴
    this->yAxis2->setTickLabels(true);    //x2轴刻度不显示文本
    this->yAxis2->setSubTicks(true);
    this->yAxis2->setTicks(true);
    this->yAxis2->setBasePen(QPen(colorLightBlue));

    connect(this->xAxis, SIGNAL(rangeChanged(QCPRange)), this->xAxis2, SLOT(setRange(QCPRange)));
    connect(this->yAxis, SIGNAL(rangeChanged(QCPRange)), this->yAxis2, SLOT(setRange(QCPRange)));
    this->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);


    //创建右键 菜单
    QAction *pActionAuto = new QAction(tr("自动缩放"));
    pActionAuto->setCheckable(true);
    pActionAuto->setChecked(m_bAutoScale);
    this->addAction(pActionAuto);
    connect(pActionAuto,&QAction::triggered,[=](bool bChecked){
        m_bAutoScale = bChecked;
    });

    m_pActionStop = new QAction(tr("停止接收"));
    m_pActionStop->setToolTip(tr("停止接收数据"));
    m_pActionStop->setCheckable(true);
    m_pActionStop->setChecked(m_bAutoScale);
    this->addAction(m_pActionStop);
    connect(m_pActionStop,&QAction::triggered,[=](bool bChecked){
        ui->pushButton_start->setChecked(!bChecked);
    });

    QAction *pActionInfo = new QAction(tr("协议说明"));
    this->addAction(pActionInfo);
    connect(pActionInfo,&QAction::triggered,[=]{
        VDialogProtocal dialog;
        dialog.exec();
    });

    QAction *pActionClear = new QAction(tr("清空"));
    pActionClear->setToolTip(tr("清空图表数据"));
    this->addAction(pActionClear);
    connect(pActionClear,&QAction::triggered,[=]{
        this->clearGraphs();
    });


   // ui->checkBox1->set
ui->checkBox1->setChecked(true);
ui->checkBox2->setChecked(true);
ui->checkBox3->setChecked(true);
ui->checkBo4->setChecked(true);
ui->checkBox5->setChecked(true);
ui->checkBox6->setChecked(true);
ui->checkBox7->setChecked(true);
ui->checkBox8->setChecked(true);
\


    //创建右键 菜单
    pActionAuto = new QAction(tr("隐藏按钮"));
    pActionAuto->setCheckable(true);
    pActionAuto->setChecked(false);
    this->addAction(pActionAuto);
    connect(pActionAuto,&QAction::triggered,[=](bool bChecked){
       // m_bAutoScale = bChecked;
        if(bChecked)
        {
            ui->pushButton_x_dec->hide();
            ui->pushButton_y_dec->hide();
            ui->pushButton_x_inc->hide();
            ui->pushButton_y_inc->hide();
            ui->pushButton_x_zero->hide();
            ui->pushButton_y_zero->hide();


        }
        else
        {
            ui->pushButton_x_dec->show();
            ui->pushButton_y_dec->show();
            ui->pushButton_x_inc->show();
            ui->pushButton_y_inc->show();
            ui->pushButton_x_zero->show();
            ui->pushButton_y_zero->show();

        }

    });

    m_bshowline[0] = true;
    m_bshowline[1] = true;
    m_bshowline[2] = true;
    m_bshowline[3] = true;
    m_bshowline[4] = true;
    m_bshowline[5] = true;
    m_bshowline[6] = true;
    m_bshowline[7] = true;

    this->protocol = 1 ;// 使用山外协议

QAction *pActionInfo1 ;
    /*创建 选择协议通道 */
    pActionInfo = new QAction(tr("山外协议"));
    pActionInfo->setToolTip(tr("使用 0x03 0xfc data..."));
    pActionInfo->setCheckable(true);
    pActionInfo->setChecked(1);
    this->addAction(pActionInfo);







    pActionInfo1 = new QAction(tr("默认协议"));
    this->addAction(pActionInfo1);
    pActionInfo1->setCheckable(true);
    pActionInfo1->setChecked(0);
    connect(pActionInfo1,&QAction::triggered,[=](bool bChecked){
        if(bChecked)
        {
            this->protocol = 2;
            pActionInfo->setChecked(0);
        }
        else
        {this->protocol = 1;
            pActionInfo->setChecked(1);
        }
    });

    connect(pActionInfo,&QAction::triggered,[=](bool bChecked){
        if(bChecked)
           {
            this->protocol = 1;
            pActionInfo1->setChecked(0);}
        else
           { this->protocol = 2;
            pActionInfo1->setChecked(1);}

    });


//    /* 创建隐藏 start*/
//    QAction *pshow_line = new QAction(tr("波形1 红"));
//    pshow_line->setToolTip((tr("隐藏波形")));
//    pshow_line->setCheckable(true);
//    pshow_line->setChecked(1);
//    this->addAction(pshow_line);

//    connect(pshow_line,&QAction::triggered,[=](bool bChecked){
//        m_bshowline[0] = bChecked; //qDebug()<<"mb show line "<<m_bshowline[0];
//        //刷新曲线
//        this->graph(0)->setVisible(bChecked);
//        this->replot();

//    });

//    /* 创建隐藏 end*/

//    /* 创建隐藏 start*/
//    pshow_line = new QAction(tr("波形2 橙"));
//    pshow_line->setToolTip((tr("隐藏波形")));
//    pshow_line->setCheckable(true);
//    pshow_line->setChecked(1);
//    this->addAction(pshow_line);

//    connect(pshow_line,&QAction::triggered,[=](bool bChecked){
//        m_bshowline[1] = bChecked; //qDebug()<<"mb show line "<<m_bshowline[0];
//        //刷新曲线
//        this->graph(1)->setVisible(bChecked);
//        this->replot(); });

//    /* 创建隐藏 end*/

//    /* 创建隐藏 start*/
//    pshow_line = new QAction(tr("波形3 黄"));
//    pshow_line->setToolTip((tr("隐藏波形")));
//    pshow_line->setCheckable(true);
//    pshow_line->setChecked(1);
//    this->addAction(pshow_line);

//    connect(pshow_line,&QAction::triggered,[=](bool bChecked){
//        m_bshowline[2] = bChecked; //qDebug()<<"mb show line "<<m_bshowline[0];
//        //刷新曲线
//        this->graph(2)->setVisible(bChecked);
//        this->replot();});

//    /* 创建隐藏 end*/
//    /* 创建隐藏 start*/
//   pshow_line = new QAction(tr("波形4 绿"));
//    pshow_line->setToolTip((tr("隐藏波形")));
//    pshow_line->setCheckable(true);
//    pshow_line->setChecked(1);
//    this->addAction(pshow_line);

//    connect(pshow_line,&QAction::triggered,[=](bool bChecked){
//        m_bshowline[3] = bChecked; //qDebug()<<"mb show line "<<m_bshowline[0];
//        //刷新曲线
//        this->graph(3)->setVisible(bChecked);
//        this->replot();});

//    /* 创建隐藏 end*/
//    /* 创建隐藏 start*/
//    pshow_line = new QAction(tr("波形5 青"));
//    pshow_line->setToolTip((tr("隐藏波形")));
//    pshow_line->setCheckable(true);
//    pshow_line->setChecked(1);
//    this->addAction(pshow_line);

//    connect(pshow_line,&QAction::triggered,[=](bool bChecked){
//        m_bshowline[4] = bChecked; //qDebug()<<"mb show line "<<m_bshowline[0];
//        //刷新曲线
//        this->graph(4)->setVisible(bChecked);
//        this->replot(); });

//    /* 创建隐藏 end*/
//    /* 创建隐藏 start*/
//    pshow_line = new QAction(tr("波形6 蓝"));
//    pshow_line->setToolTip((tr("隐藏波形")));
//    pshow_line->setCheckable(true);
//    pshow_line->setChecked(1);
//    this->addAction(pshow_line);

//    connect(pshow_line,&QAction::triggered,[=](bool bChecked){
//        m_bshowline[5] = bChecked; //qDebug()<<"mb show line "<<m_bshowline[0];
//        //刷新曲线
//        this->graph(5)->setVisible(bChecked);
//        this->replot();});

//    /* 创建隐藏 end*/
//    /* 创建隐藏 start*/
//   pshow_line = new QAction(tr("波形7 紫"));
//    pshow_line->setToolTip((tr("隐藏波形")));
//    pshow_line->setCheckable(true);
//    pshow_line->setChecked(1);
//    this->addAction(pshow_line);

//    connect(pshow_line,&QAction::triggered,[=](bool bChecked){
//        m_bshowline[6] = bChecked; //qDebug()<<"mb show line "<<m_bshowline[0];
//        //刷新曲线
//        this->graph(6)->setVisible(bChecked);
//        this->replot();});

//    /* 创建隐藏 end*/

//    /* 创建隐藏 start*/
//   pshow_line = new QAction(tr("波形8 粉"));
//    pshow_line->setToolTip((tr("隐藏波形")));
//    pshow_line->setCheckable(true);
//    pshow_line->setChecked(1);
//    this->addAction(pshow_line);

//    connect(pshow_line,&QAction::triggered,[=](bool bChecked){
//        m_bshowline[7] = bChecked; //qDebug()<<"mb show line "<<m_bshowline[0];
//        //刷新曲线
//        this->graph(7)->setVisible(bChecked);
//        this->replot();});

    /* 创建隐藏 end*/












    this->setContextMenuPolicy(Qt::ActionsContextMenu);

}

//void VCharts::dataArrive(QString strIp, quint16 nPort, QByteArray byteTmp)
//{
//    Q_UNUSED(strIp)
//    Q_UNUSED(nPort)

//    if(m_pActionStop->isChecked())
//        return ;

//    //将数据添加到缓冲区
//    m_bufCache.buffer().append(byteTmp);

//    QByteArray byteArr;
//    if(m_bufCache.open(QIODevice::ReadWrite)){
//            if(m_bufCache.canReadLine()){
//                byteArr = m_bufCache.readLine();
//                m_bufCache.buffer().remove(0,byteArr.size());
//                byteArr.remove(byteArr.size() - 1,1); //删除\n
////                qDebug()<<"读出行"<<byteArr;
//            }else{
////                qDebug()<<"未读出行";
//                return ;
//            }
//            m_bufCache.close();
//    }




//    //读出一行  解析画出来
//    static QStringList strArrColor = {"#00dcc5","#2a8cfa","#633399","#ff3838","#e3dd35","#00dc58","#dc01c0","#00dcc5"};
//    QList<QByteArray> listValue = byteArr.split(',');
//    qDebug()<<listValue;
//    if(this->graphCount() != listValue.count()){
//        this->clearGraphs();
//    }
//    while(this->graphCount() != listValue.count()){
//        QCPGraph *pCPGraph = this->addGraph(); //颜色随机
//        pCPGraph->setPen(QPen(QColor(strArrColor[this->graphCount()%strArrColor.count()])));
//        connect(this->xAxis, SIGNAL(rangeChanged(QCPRange)), this->xAxis2, SLOT(setRange(QCPRange)));
//        connect(this->yAxis, SIGNAL(rangeChanged(QCPRange)), this->yAxis2, SLOT(setRange(QCPRange)));
//    }
//    for(int i = 0;  i < listValue.size(); i++){
//        double dKey,dVal;
//        dKey = this->graph(i)->dataCount() + 1;
//        bool bOk;
//        dVal = listValue[i].toDouble(&bOk);

//        if(bOk){
//            this->graph(i)->addData(dKey,dVal);
//            this->graph(i)->rescaleAxes(m_bAutoScale); //是否 自动缩放纵横轴
//            qDebug()<<"dkey:"<<dKey<<"dVal:"<<dVal;
//            this->xAxis->setRange(dKey, 100, Qt::AlignRight);
//        }
//    }

//    //刷新曲线
//    this->replot();
//}


typedef union
{
   uint8_t c_d[4];
   float f_d;
}uinon_data;

void VCharts::dataArrive(QString strIp, quint16 nPort, QByteArray byteTmp)
{
    Q_UNUSED(strIp)
    Q_UNUSED(nPort)
    static QStringList strArrColor = {"#ff3838","#fdc009","#f3ed05","#00dc00","#00dcc5","#2a8cfa","#933099","#dc01c0"};
    static uint8_t chanel_num = 0; // 通道数量

    if(m_pActionStop->isChecked())
        return ;

    //将数据添加到缓冲区
    m_bufCache.buffer().append(byteTmp);
//1  兼容山外调试助手的波形协议

 //2  支持隐藏部分波形
 QByteArray byteArr;

    if(this->protocol == 1) // 使用山外协议
    {
        // 03 fc data 低位在前  fc 03 -> 1,2,3,4\r\n

        if(m_bufCache.open(QIODevice::ReadWrite)){
              QByteArray ba =   m_bufCache.readAll();
              int head_p = 0,tail_p = 0;

              // 寻找帧头
              for(int i = 0;i <ba.size()-1; i++)
              {
                  if((uint8_t)ba.at(i) == 0x03 && (uint8_t)ba.at(i+1) == 0xfc)
                  {
                  head_p = i;
                  break;
                  }

              }
              // 寻找帧尾
              for(int i = head_p;i <ba.size()-1; i++)
              {
                  if((uint8_t)ba.at(i) == 0xfc && (uint8_t)ba.at(i+1) == 0x03)
                  {
                  tail_p = i;
                  break;
                  }

              }

              float wave_data[8] = {0};
              QString str = "";
              // 判断长度
              if((tail_p - head_p)>=4) // 数据有效, 至少一个通道的数据
              {
                    uinon_data ua;
                  for( int i = 0; i < (tail_p - head_p)/4;i++)
                  {

                      ua.c_d[0] = (uint8_t)ba.at(i*4 + head_p+2);
                      ua.c_d[1] = (uint8_t)ba.at(i*4 + head_p+3);
                      ua.c_d[2] = (uint8_t)ba.at(i*4 + head_p+4);
                      ua.c_d[3] = (uint8_t)ba.at(i*4 + head_p+5);
                    wave_data[i] = ua.f_d;

                    str += QString("%1,").arg(wave_data[i]);

                  }
                  str.chop(1);

                  str += QString("\r\n");
              }

              qDebug()<<"---------"<<str<<"head tail"<<head_p<<"  "<<tail_p;

              byteArr =str.toLatin1();

            //  m_bufCache.readAll()

            /////////////////////////////////////////
//                if(m_bufCache.canReadLine()){
//                    byteArr = m_bufCache.readLine();
//                    m_bufCache.buffer().remove(0,byteArr.size());
//                    byteArr.remove(byteArr.size() - 1,1); //删除\n
//    //                qDebug()<<"读出行"<<byteArr;
//                }else{
//    //                qDebug()<<"未读出行";
//                    return ;
//                }
//                m_bufCache.close();
        }



    }
    else if(this->protocol == 2) // 使用默认协议
    {


    /*原始数据 03 fc  data fc 03  */

    if(m_bufCache.open(QIODevice::ReadWrite)){
            if(m_bufCache.canReadLine()){
                byteArr = m_bufCache.readLine();
                m_bufCache.buffer().remove(0,byteArr.size());
                byteArr.remove(byteArr.size() - 1,1); //删除\n
//                qDebug()<<"读出行"<<byteArr;
            }else{
//                qDebug()<<"未读出行";
                return ;
            }
            m_bufCache.close();
    }


}

    //读出一行  解析画出来

    QList<QByteArray> listValue = byteArr.split(',');
    qDebug()<<listValue;


    if(this->graphCount() != listValue.count()){
        this->clearGraphs();
    }
    while(this->graphCount() != listValue.count()){
        QCPGraph *pCPGraph = this->addGraph(); //颜色随机
        pCPGraph->setPen(QPen(QColor(strArrColor[this->graphCount()-1])));
        connect(this->xAxis, SIGNAL(rangeChanged(QCPRange)), this->xAxis2, SLOT(setRange(QCPRange)));
        connect(this->yAxis, SIGNAL(rangeChanged(QCPRange)), this->yAxis2, SLOT(setRange(QCPRange)));
    }
   // /




    for(int i = 0;  i < listValue.size(); i++){
        double dKey,dVal;
        dKey = this->graph(i)->dataCount() + 1;
        bool bOk;
        dVal = listValue[i].toDouble(&bOk);

        if(bOk){
//           this->graph(i)->setVisible(1);
            this->graph(i)->addData(dKey,dVal);
            this->graph(i)->rescaleAxes(m_bAutoScale); //是否 自动缩放纵横轴
            qDebug()<<"dkey:"<<dKey<<"dVal:"<<dVal;
            this->xAxis->setRange(dKey, 100, Qt::AlignRight);
        }
    }

    //刷新曲线
    this->replot();
}
void VCharts::on_pushButton_start_toggled(bool checked)
{
    m_pActionStop->setChecked(!checked);
    if(checked){
        ui->pushButton_start->hide();
    }else{
        ui->pushButton_start->show();
    }
}

void VCharts::on_pushButton_y_zero_clicked()
{
    this->yAxis->setRange(-100,100);
    this->replot();
}

void VCharts::on_pushButton_x_zero_clicked()
{
    this->xAxis->setRange(0,100);
    this->replot();
}

void VCharts::on_pushButton_y_inc_clicked()
{

    this->yAxis->scaleRange(1.2);
    this->replot();
}

void VCharts::on_pushButton_y_dec_clicked()
{
    this->yAxis->scaleRange(0.8);
    this->replot();
}

void VCharts::on_pushButton_x_inc_clicked()
{
    this->xAxis->scaleRange(1.2);
    this->replot();
}

void VCharts::on_pushButton_x_dec_clicked()
{
    this->xAxis->scaleRange(0.8);
    this->replot();
}

void VCharts::on_checkBox1_stateChanged(int arg1)
{
    if(ui->checkBox1->isChecked())
    {
        if(this->graphCount()>= 1)
        {
        this->graph(0)->setVisible(true);
        this->replot(); //   qDebug()<<"check on";
        }
    }
    else
    {
        if(this->graphCount()>= 1)
        {
        this->graph(0)->setVisible(false);
        this->replot();  // qDebug()<<"check off";
}
    }
}
